<template>
	<view class="container">
		<view class="intro">ESP32 点灯项目</view>
		<view class="box">
			<u-button type="primary" text="连接" class="btn" @click="MqttConnect()"></u-button>
			<u-button type="warning" text="开关" class="btn" @click="led_on_off()"></u-button>
		</view>
	</view>

	
</template>

<script>
	import { v4 } from "uuid"; 
	const mqtt = require('mqtt/dist/mqtt.js');
	const options = {
		clean:true,
		connectTimeout :4000,
		clientId:'',
		keepalive:40,
		username:'',
		password:'',
		topic:'testtopic',
		will:{
			topic :'MiniLast',
			payload:'Connection Closed abnormally ...',
			retain :false,
			qos:0
		}
	};
	export default {
		data() {
			return {
				client:null,
				flag:true
			}
		},
		methods: {
			

			MqttConnect(){
				console.log("开始连接...");
				this.connect()
			},
			led_on_off(){
				if(this.flag){
					this.client.publish('esp32Demo',"0");
					this.flag = false;
				}
				else{
					this.client.publish('esp32Demo',"1");
					this.flag = true;
				}
				
			},
			connect() {
				let that = this;
				options.clientId = v4()
				console.log('options.clientId = '+options.clientId)
				// #ifdef H5
				// H5使用ws及websocket协议 
				this.client = mqtt.connect('ws://localhost:8083/mqtt',options)
				// #endif
				// #ifdef MP-WEIXIN || APP-PLUS
				//微信小程序及app使用wx协议 
				this.client = mqtt.connect('wx://localhost:8083/mqtt',options)
				// #endif
				
				this.client.on('connect',function(mes){
					console.log('mqtt已连接');
					that.client.subscribe("esp32Demo");
				})
				this.client.on('reconnect',(error)=>{
					console.log('正在重连:',error);
				})
				this.client.on('message',(topic,message)=>{
					console.log('收到消息:',topic,message.toString());
				})
				
			}
		},
		}
</script>

<style lang="scss";>
	.container {
		padding: 20px;
		font-size: 50rpx;
		line-height: 24px;
		margin: 10px;
		.box {
			margin-top: 20px;
			.btn {
				margin: 10px;
			}
		}
	}
</style>
